/*
 * Copyright (c) 2011 Ondrej Lapacek
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you
 * may not use this file except in compliance with the License. You may
 * obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

/**
 * @author      Ondrej Lapacek
 * @version     1.0, 09/12/11
 * @since       1.0
 */

package cz.muni.fi.android.assistivecamera.gallery;

import java.io.File;
import java.io.FilenameFilter;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import cz.muni.fi.android.assistivecamera.R;
import cz.muni.fi.android.assistivecamera.dialog.BlindDialog;
import cz.muni.fi.android.assistivecamera.dialog.ResponseEventListener;
import cz.muni.fi.android.assistivecamera.texttospeech.SpeechHandler;

public class AssistiveGalleryActivity extends Activity implements ResponseEventListener {
	
	private CustomGallery gallery = null;
	private ImageAdapter myImageAdapter = null;
	private boolean isEmpty = false;
	
	private static BlindDialog customizeDialog = null;
	
	private static Context ctx;
	
	private MediaPlayer mpButton = null; 
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gallery);
        
        ctx = this;
        
        mpButton = MediaPlayer.create(ctx, R.raw.button_click);
        
        SpeechHandler.ttsQueue(ctx.getResources().getString(R.string.startGallery), 1, 0);
        
        gallery = (CustomGallery) findViewById(R.id.gallery);
        if (readSDCard().length != 0) {
        	myImageAdapter = new ImageAdapter(this, readSDCard());
        	gallery.setAdapter(myImageAdapter);
        	gallery.setFadingEdgeLength(0);  
	 
        	gallery.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
					ExifReader exifReader = new ExifReader();
			    	exifReader.extractExif(parent.getItemAtPosition(position).toString(), ctx);
	            }
	        });
        } else {
        	SpeechHandler.ttsQueue(ctx.getResources().getString(R.string.noImageGallery), 1, 1);
        	isEmpty = true;
        }
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent keyEvent) {
    	super.onKeyDown(keyCode, keyEvent);
    	
    	switch (keyCode) {
    	case KeyEvent.KEYCODE_MENU : 
    		mpButton.start();
    		if (!isEmpty) {
    			SpeechHandler.ttsQueue(ctx.getResources().getString(R.string.deletePhotoDialog), 0, 0);
            	SpeechHandler.ttsQueue(ctx.getResources().getString(R.string.deletePhoto), 1, 0);
            	SpeechHandler.ttsQueue(ctx.getResources().getString(R.string.deleteAllPhotos), 1, 0);
            	
            	builtDeleteDialog();
    		}
    		return true;
        case KeyEvent.KEYCODE_I : 
        	mpButton.start();
        	if (!isEmpty) {
        		int index = gallery.getSelectedItemPosition();
        		ExifReader exifReader = new ExifReader();
		    	exifReader.extractExif(myImageAdapter.getItem(index).toString(), ctx);
    		}
        	return true;
    	}
    	return true;
    }
    
    public void builtDeleteDialog() {
    	String title = ctx.getResources().getString(R.string.deletePhotoDialog);
    	String[] names = {ctx.getResources().getString(R.string.deletePhoto), 
    			ctx.getResources().getString(R.string.deleteAllPhotos),
    			ctx.getResources().getString(R.string.cancelDelete)};
        customizeDialog = new BlindDialog(ctx, this, title, names);
        customizeDialog.setCancelable(true);
        customizeDialog.show();
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        boolean previouslyStarted = prefs.getBoolean(getString(R.string.pref_previously_started_gallery), false);
        if (!previouslyStarted) {
        	SharedPreferences.Editor edit = prefs.edit();
            edit.putBoolean(getString(R.string.pref_previously_started_gallery), Boolean.TRUE);
            edit.commit();
            
            SpeechHandler.ttsQueue(ctx.getResources().getString(R.string.firstStartUpGallery), 1, 1);
        }
    }
    
    @Override
    protected void onPause() {
        super.onResume();
        SpeechHandler.getInstance().ttsStop();
        
        if (customizeDialog != null)
	        if(customizeDialog.isShowing()) {
	        	customizeDialog.dismiss();
	        }
    }
    
    private Uri[] readSDCard() {  
    	String state = Environment.getExternalStorageState();
    	
    	if( Environment.MEDIA_MOUNTED.equals(state) ) {
    		String[] mFiles=null;
    		Uri[] mUrls; 
    		
    		File images = new File(Environment.getExternalStorageDirectory() + "/DCIM/BlindPhoto/"); 
    		images.mkdirs();
    		
            File[] imagelist = images.listFiles(new FilenameFilter() {   
	            public boolean accept(File dir, String name) {  
	                return name.endsWith(".jpg");
	            }  
            });  
            mFiles = new String[imagelist.length];  
      
            for(int i = 0 ; i < imagelist.length; i++) {  
                mFiles[i] = imagelist[i].getAbsolutePath();  
            }  
            mUrls = new Uri[mFiles.length];  
      
            for(int i = 0; i < mFiles.length; i++) {  
                mUrls[i] = Uri.parse(mFiles[i]);     
            }  
		    
		    return mUrls; 
    	}
    	
    	return null;
    }

	@Override
	public void responseEvent(String response) {
		customizeDialog.hide();
		customizeDialog.dismiss();
		if (response.equals(ctx.getResources().getString(R.string.deletePhoto))) {
			String state = Environment.getExternalStorageState();
        	if( Environment.MEDIA_MOUNTED.equals(state) && Environment.MEDIA_MOUNTED_READ_ONLY.equals(state) != true) {
				String fileToBeDeleted = gallery.getItemAtPosition(gallery.getSelectedItemPosition()).toString();
				File picFile = new File(fileToBeDeleted);
				String exifToBeDeleted = picFile.getAbsolutePath().replaceFirst("[.][^.]+$", "");
				File exifFile = new File(exifToBeDeleted);
				
				picFile.delete();
				exifFile.delete(); 

				if (readSDCard().length != 0) {
					myImageAdapter = new ImageAdapter(AssistiveGalleryActivity.this, readSDCard());
					gallery.setAdapter(myImageAdapter);
					gallery.setFadingEdgeLength(0);
				} else {
					myImageAdapter = new ImageAdapter(AssistiveGalleryActivity.this, readSDCard());
					gallery.setAdapter(myImageAdapter);
					
	                SpeechHandler.ttsQueue(ctx.getResources().getString(R.string.noImageGallery), 0, 1);
					isEmpty = true;
				}
        	}
		} else if (response.equals(ctx.getResources().getString(R.string.deleteAllPhotos))) {
            String state = Environment.getExternalStorageState();
            if( Environment.MEDIA_MOUNTED.equals(state) && Environment.MEDIA_MOUNTED_READ_ONLY.equals(state) != true) {
            	File images = new File(Environment.getExternalStorageDirectory() + "/DCIM/BlindPhoto/"); 
        		images.mkdirs();
        		
                File[] imagelist = images.listFiles(new FilenameFilter() {   
    	            public boolean accept(File dir, String name) {  
    	                return name.endsWith(".jpg");
    	            }  
                });   
          
                for(int i = 0 ; i < imagelist.length; i++) {  
					File picFile = new File(imagelist[i].getAbsolutePath());
					String exifToBeDeleted = picFile.getAbsolutePath().replaceFirst("[.][^.]+$", "");
					File exifFile = new File(exifToBeDeleted);
					
					picFile.delete();
					exifFile.delete();  
                }

                myImageAdapter = new ImageAdapter(AssistiveGalleryActivity.this, readSDCard());
				gallery.setAdapter(myImageAdapter);
				
                SpeechHandler.ttsQueue(ctx.getResources().getString(R.string.noImageGallery), 0, 1);
                isEmpty = true;
        	}
		}
	}
}